#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
fbs跨平台打包脚本
使用fbs将PyQt5应用打包为跨平台应用程序
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path

def setup_fbs_project():
    """设置fbs项目结构"""
    print("设置fbs项目结构...")
    
    # 检查是否已经初始化过fbs项目
    src_dir = Path("src")
    if src_dir.exists():
        print("fbs项目结构已存在，跳过初始化")
        return True
    
    # 初始化fbs项目
    try:
        subprocess.run(["fbs", "startproject"], check=True)
        print("fbs项目初始化成功")
    except subprocess.CalledProcessError as e:
        print(f"fbs项目初始化失败: {e}")
        return False
    
    # 复制应用程序代码到fbs项目结构中
    try:
        # 创建main目录
        main_dir = Path("src/main/python")
        main_dir.mkdir(parents=True, exist_ok=True)
        
        # 复制app.py到main目录
        shutil.copy("app.py", main_dir / "main.py")
        
        # 创建图标目录
        icons_dir = Path("src/main/icons")
        if not icons_dir.exists():
            icons_dir.mkdir(parents=True, exist_ok=True)
        
        # 如果有图标文件，复制到fbs图标目录
        app_icon_dir = Path("icons")
        if app_icon_dir.exists():
            for icon_file in app_icon_dir.glob("*"):
                shutil.copy(icon_file, icons_dir)
        
        print("应用程序代码已复制到fbs项目结构中")
    except Exception as e:
        print(f"复制应用程序代码失败: {e}")
        return False
    
    return True

def build_with_fbs(target_platform=None):
    """使用fbs打包应用"""
    if not setup_fbs_project():
        return False
    
    print(f"开始使用fbs打包{'所有平台' if target_platform is None else target_platform}应用...")
    
    # 构建命令
    cmd = ["fbs", "freeze"]
    
    # 如果指定了目标平台
    if target_platform:
        cmd.append(f"--target={target_platform}")
    
    # 执行打包命令
    try:
        subprocess.run(cmd, check=True)
        print(f"应用打包成功！")
        
        # 创建安装程序
        if target_platform in (None, "windows"):
            subprocess.run(["fbs", "installer"], check=True)
            print("Windows安装程序创建成功！")
        
        if target_platform in (None, "mac"):
            subprocess.run(["fbs", "dmg"], check=True)
            print("macOS DMG安装包创建成功！")
        
        if target_platform in (None, "linux"):
            subprocess.run(["fbs", "installer"], check=True)
            print("Linux安装程序创建成功！")
        
    except subprocess.CalledProcessError as e:
        print(f"打包失败: {e}")
        return False
    
    return True

if __name__ == "__main__":
    # 解析命令行参数
    target = None
    if len(sys.argv) > 1:
        target = sys.argv[1]
        if target not in ("windows", "mac", "linux"):
            print(f"不支持的目标平台: {target}")
            print("支持的平台: windows, mac, linux")
            sys.exit(1)
    
    # 执行打包
    success = build_with_fbs(target)
    sys.exit(0 if success else 1)